package handler

import (
	"github.com/sirupsen/logrus"
	"net"
	"net/http"
	"time"
)

type HttpServer interface {
	Start()
	Stop()
}
type httpServer struct {
	server *http.Server
}

func NewServer() HttpServer {
	return &httpServer{}
}

func (hs *httpServer) Start() {
	http.Handle("/GetMap", new(GetMapHandler))
	http.Handle("/talkInfo", new(TalkHandler))
	http.Handle("/ws", new(webSocketHandler))
	hs.server = &http.Server{
		Addr:           "0.0.0.0:6030",
		Handler:        http.DefaultServeMux,
		ReadTimeout:    10 * time.Minute,
		WriteTimeout:   10 * time.Minute,
		MaxHeaderBytes: 1 << 20,
	}

	listener, err := net.Listen("tcp", hs.server.Addr)
	if err != nil {
		logrus.Fatalf("Failed to start HTTP server: %v", err)
	}

	err = hs.server.Serve(listener)
	if err != nil && err != http.ErrServerClosed {
		logrus.Errorf("HTTP server error: %v", err)
	} else {
		logrus.Debug("HTTP Server Running")
	}
}

func (hs *httpServer) Stop() {
	if hs.server != nil {
		err := hs.server.Shutdown(nil)
		if err != nil {
			logrus.Errorf("HTTP server shutdown error: %v", err)
		}
	}
}
